package base.action.lib;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import net.sf.json.JSONArray;
import org.hibernate.id.UUIDHexGenerator;
import base.db.lib.DBHelper;
import base.db.lib.util.ConncenFactory;
import base.db.lib.util.DBConnection;
import base.util.lib.DateUtil;
import base.util.lib.Pager;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("all")
public class BaseAction extends ActionSupport implements java.io.Serializable {

	/**
	 * 序列UID
	 */
	private static final long serialVersionUID = 7685501346052394846L;

	/**
	 * 返回传入对象的字符串 若该对象为空则返回空字符串
	 * 
	 * @param obj
	 *            传入对象
	 * @return String 返回字符串
	 */
	public static String getValue(Object obj) {
		return obj == null ? "" : obj.toString().trim();
	}
	/**
	 * 设置ajax操作结果字符串信息 true时返回信息设为yes false时返回信息设为no
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 * @param b
	 *            传入boolean值
	 */
	public void setAjaxBoolean(boolean b) {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		if (b) {
			request.setAttribute("ajax", "yes");
		} else {
			request.setAttribute("ajax", "no");
		}
	}
	/**
	 * 设置ajax操作结果字符串信息
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 * @param String ajax
	 *            
	 */
	public void setAjaxMessage(String ajax) {
		HttpServletRequest request = HttpRequestFactory.getRequest();
			request.setAttribute("ajax", ajax);
	}

	/**
	 * 设置ajax操作结果字符串信息 传入参数错误 设置信息为 param_error
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 */
	public void setAjaxParamError() {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		request.setAttribute("ajax", "param_error");
	}
	/**
	 * 设置ajax操作结果单个对象信息 若操作结果为对象 将其转化为json list并放入ajax中
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 * @param obj
	 *            传入单个对象
	 */
	public void setAjaxObj(Object obj) {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		JSONArray jsonList = JSONArray.fromObject(obj); // 数据obj转化为json list
		request.setAttribute("ajax", jsonList);
	}

	/**
	 * 设置ajax操作结果list信息 若操作结果为list结果集 将其转化为json list并放入ajax中
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 * @param list
	 *            传入list结果集
	 */
	@SuppressWarnings("unchecked")
	public void setAjaxList(List list) {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		if (list != null && list.size() > 0) {
			JSONArray jsonList = JSONArray.fromObject(list); // 数据list转化为json 													// list
			request.setAttribute("ajax", jsonList);
		}
	}

	/**
	 * 传入HttpServletRequest请求返回session会话
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 * @return HttpSession session会话
	 */
	public HttpSession getSession() {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		return request.getSession();
	}

	/**
	 * 传入HttpServletRequest请求清空所有session
	 * 
	 * @param request
	 *            HttpServletRequest请求
	 */
	@SuppressWarnings("unchecked")
	public void clearSession() {
		Enumeration e = this.getSession().getAttributeNames();
		while (e.hasMoreElements()) {
			String sessionName = (String) e.nextElement();
			this.getSession().removeAttribute(sessionName);
		}
	}

	/**
	 * hibernate 生成 uuid 32 位唯一字符串
	 * 
	 * @return String 32 位唯一字符串
	 */
	public String getGenerateId() {
		return (new UUIDHexGenerator()).generate(null, null).toString();
	}

	/*******************************************************************************************************
	 * *************************************************************************
	 * **************************** 查询时设置查询字段参数操作
	 * *******************************
	 * **********************************************************************
	 * ***
	 * ***********************************************************************
	 * ***************************
	 */
	/**
	 * 查询时设置查询字段参数操作 页面中传入查询 字段格式为 search_1_fdh search 表示查询 1 表示 like 2 表示 = 3表示
	 * >= 4表示 <=
	 * 
	 * @param sql
	 *            查询sql语句
	 * @param params
	 *            查询字段值列表
	 */
	@SuppressWarnings("unchecked")
	public void setSearchParams(StringBuilder sql, Vector params) {
		if (sql == null)
			return;
		if (params == null)
			return;
		HttpServletRequest request = HttpRequestFactory.getRequest();
		Map map = request.getParameterMap();
		Set s = map.keySet();
		Iterator it = s.iterator();
		String search_field = "";
		while (it.hasNext()) {
			search_field = (String) it.next();
			if (search_field.length() < 10) { // select_1_ 传入参数格式必须不小于10
				continue;
			}
			int index = search_field.indexOf("search_");
			if (index == 0) {
				String temp_sql = "";
				String temp_operation = ""; // 1 like 2 =
				String temp_field = "";
				String temp_param = "";
				temp_operation = search_field.substring(7, 8);
				temp_field = search_field.substring(9, search_field.length());
				temp_param = getValue(request.getParameter(search_field));
				if (temp_operation.equals("1")) { // =
					if (!temp_param.equals("")) {
						temp_sql = " and t." + temp_field + " = ? ";
						sql.append(temp_sql);
						params.add(temp_param);
					}
				} else if (temp_operation.equals("2")) { // like
					if (!temp_param.equals("")) {
						temp_sql = " and t." + temp_field + " like ? ";
						sql.append(temp_sql);
						params.add("%" + temp_param + "%");
					}
				} else if (temp_operation.equals("3")) { // >=
					if (!temp_param.equals("")) {
						temp_sql = " and t." + temp_field + " >= ? ";
						sql.append(temp_sql);
						params.add(temp_param);
					}
				} else if (temp_operation.equals("4")) { // <=
					if (!temp_param.equals("")) {
						temp_sql = " and t." + temp_field + " <= ? ";
						sql.append(temp_sql);
						params.add(temp_param);
					}
				}
			}
		}
	}

	/*******************************************************************************************************
	 * *************************************************************************
	 * **************************** 增加、修改时设置传入字段参数操作
	 * ****************************
	 * *************************************************************************
	 * *************************************************************************
	 * ****************************
	 */
	/**
	 * 增加、修改时设置传入字段参数操作 页面中传入字段格式为 vch_fdh、num_fdh vch 表示此字段类型为字符串 fdh 表示字段
	 * 
	 * @param cols
	 *            增加、修改字段列表
	 * @param params
	 *            增加、修改字段值列表
	 * @param dataField
	 *            时间字段
	 */
	@SuppressWarnings("unchecked")
	public void setInsertOrUpdateParams(List cols, Vector params,
			String dateField) {
		if (cols == null)
			return;
		if (params == null)
			return;

		HttpServletRequest request = HttpRequestFactory.getRequest();
		Map map = request.getParameterMap();
		Set s = map.keySet();
		Iterator it = s.iterator();
		String col = "";
		while (it.hasNext()) {
			col = (String) it.next();
			int index = col.indexOf("_");
			if (index == -1) {
				continue;
			}
			String value = getValue(request.getParameter(col));
			cols.add(col.substring(index + 1, col.length()));
			if (col.indexOf("num_") == 0) {
				if (StringUtils.isEmpty(value)) {
					params.add(value);
				} else {
					BigDecimal big = new BigDecimal(value);
					params.add(big);
				}
			}else if (col.indexOf("dt_") == 0) {
					if (StringUtils.isEmpty(value)) {
						params.add(value);
					} else {
						Date date = DateUtil.getDate(value);
						params.add(date);
					}
			}else if (col.indexOf("dti_") == 0) {// yyyy-MM-dd
					if (StringUtils.isEmpty(value)) {
						params.add(value);
						
					} else {
						Date date = DateUtil.getDate(value, "yyyy-MM-dd");
						params.add(date);
					}
			}else if (col.indexOf("isov_") == 0) {// 如果 表单提交 出现乱码
				try {
					params.add(new String(value.getBytes("ISO-8859-1"),"utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					params.add("");
				}

			} else {
				params.add(value);
			}
		}
		// dateField 不为空时，为此字段添加时间
		if (!getValue((dateField)).equals("")) {
			cols.add(dateField);
			params.add(new Date());
		}
	}

	/*******************************************************************************************************
	 * *************************************************************************
	 * **************************** 增加、修改时设置传入字段参数操作
	 * ****************************
	 * *************************************************************************
	 * *************************************************************************
	 * ****************************
	 */
	/**
	 * 增加、修改时设置传入字段参数操作 页面中传入字段格式为 vch_fdh、num_fdh vch 表示此字段类型为字符串 fdh 表示字段
	 * 
	 * @param cols
	 *            增加、修改字段列表
	 * @param params
	 *            增加、修改字段值列表
	 * @param dataField
	 *            时间字段
	 * @param paramObject
	 *            key ---value
	 */
	@SuppressWarnings("unchecked")
	public void setInsertOrUpdateParams(List cols, Vector params,
			String dateField, Map paramObject) {
		if (cols == null)
			return;
		if (params == null)
			return;
		HttpServletRequest request = HttpRequestFactory.getRequest();
		Map map = request.getParameterMap();
		Set s = map.keySet();
		Iterator it = s.iterator();
		String col = "";
		while (it.hasNext()) {
			col = (String) it.next();
			int index = col.indexOf("_");
			if (index == -1) {
				continue;
			}
			// 去除 没有值的名称
			if (col != null && col.indexOf("_8select8") > -1) {
				continue;
			}
			String value = getValue(request.getParameter(col));
			String colum = col.substring(index + 1, col.length());// 列名
			cols.add(col.substring(index + 1, col.length()));
			if (col.indexOf("num_") == 0) {
				if (StringUtils.isEmpty(value)) {
					params.add(value);
					paramObject.put(colum, value);
				} else {
					BigDecimal big = new BigDecimal(value);
					params.add(big);
					paramObject.put(colum, big);
				}
			} else if (col.indexOf("dt_") == 0) {// yyyy-MM-dd HH:mm:ss
				if (StringUtils.isEmpty(value)) {
					params.add(value);
					paramObject.put(colum, value);
				} else {
					Date date = DateUtil.getDate(value);
					params.add(date);
					paramObject.put(colum, date);
				}
			} else if (col.indexOf("dti_") == 0) {// yyyy-MM-dd
				if (StringUtils.isEmpty(value)) {
					params.add(value);
					paramObject.put(colum, value);
				} else {
					Date date = DateUtil.getDate(value, "yyyy-MM-dd");
					params.add(date);
					paramObject.put(colum, date);
				}
			} else if (col.indexOf("isov_") == 0) {// 如果 表单提交 出现乱码
				try {
					params.add(new String(value.getBytes("ISO-8859-1"),"utf-8"));
					paramObject.put(colum, new String(value.getBytes("ISO-8859-1"), "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					params.add("");
					paramObject.put(colum, "");
				}

			} else {
				params.add(value);
				paramObject.put(colum, value);
			}
		}
		// dateField 不为空时，为此字段添加时间
		if (!getValue((dateField)).equals("")) {
			cols.add(dateField);
			params.add(new Date());
		}
	}
	/**
	 * 增加、修改时设置传入字段参数操作 页面中传入字段格式为 vch_fdh、num_fdh vch 表示此字段类型为字符串 fdh 表示字段 
	 *@param  paramObject ---map 页面参数设置为map 对象
	 */
	@SuppressWarnings("unchecked")
	public void setInsertOrUpdateParams(Map paramObject) {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		Map map = request.getParameterMap();
		Set s = map.keySet();
		Iterator it = s.iterator();
		String col = "";
		while (it.hasNext()) {
			col = (String) it.next();
			int index = col.indexOf("_");
			if (index == -1) {
				continue;
			}
			// 去除 没有值的名称
			if (col != null && col.indexOf("_8select8") > -1) {
				continue;
			}
			String value = getValue(request.getParameter(col));
			String colum = col.substring(index + 1, col.length());// 列名
			if (col.indexOf("num_") == 0) {
				if (StringUtils.isEmpty(value)) {
					paramObject.put(colum, value);
				} else {
					BigDecimal big = new BigDecimal(value);
					paramObject.put(colum, big);
				}
			} else if (col.indexOf("dt_") == 0) {// yyyy-MM-dd HH:mm:ss
				if (StringUtils.isEmpty(value)) {
					paramObject.put(colum, value);
				} else {
					Date date = DateUtil.getDate(value);
					paramObject.put(colum, date);
				}
			} else if (col.indexOf("dti_") == 0) {// yyyy-MM-dd
				if (StringUtils.isEmpty(value)) {
					paramObject.put(colum, value);
				} else {
					Date date = DateUtil.getDate(value, "yyyy-MM-dd");
					paramObject.put(colum, date);
				}
			} else if (col.indexOf("isov_") == 0) {// 如果 表单提交 出现乱码
				try {
					paramObject.put(colum, new String(value.getBytes("ISO-8859-1"), "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					paramObject.put(colum, "");
				}
			} else {
				paramObject.put(colum, value.trim()); //?????
			}
		}
	}

	/**
	 * 分页 设置分页数据
	 * 
	 * @param sql
	 *            sql语句
	 * @param params
	 *            参数
	 * @param pageId
	 *            Pager对象的ID
	 * @param arrayId
	 *            List集合对象的ID
	 */
	@SuppressWarnings("unchecked")
	public void setPageData(String sql, Vector params, String pageId,
			String arrayId,String oderbystr) {
		HttpServletRequest request =  HttpRequestFactory.getRequest();
		String pageNumStr = request.getParameter("pageNum");
		String numPerPageStr = request.getParameter("numPerPage");
		Pager pager = null;
		if (request.getSession().getAttribute(pageId) != null&& StringUtils.isNotEmpty(request.getSession().getAttribute(pageId).toString())) {
			pager = (Pager) request.getSession().getAttribute(pageId);
		} else {
			pager = new Pager(10, 10);
		}
		if (StringUtils.isNotEmpty(pageNumStr)) {
			pager.setCurrentPage(Integer.parseInt(pageNumStr));
		}
		if (StringUtils.isNotEmpty(numPerPageStr)) {
			pager.setPageSize(Integer.parseInt(numPerPageStr));
		}
		request.getSession().setAttribute(pageId, "");
		// mysql oracle 
		//List list = DBHelper.list(sql, params, pager);
		//sql2005 sql2008
		List list = DBHelper.list_sql(sql, params, pager,oderbystr);
		request.getSession().setAttribute(pageId, pager);
		if (StringUtils.isEmpty(arrayId)) {
			arrayId = "list";
		}
		request.setAttribute(arrayId, list);
	}

	
	
	/**
	 * 分页 设置分页数据
	 * 
	 * @param sql
	 *            sql语句
	 * @param params
	 *            参数
	 * @param pageId
	 *            Pager对象的ID
	 * @param arrayId
	 *            List集合对象的ID
	 * @param pageSize int 
	 *           每页多少条数据
	 * @param currentPage int 
	 *           当前第几页
	 */
	@SuppressWarnings("unchecked")
	public void setPageData(String sql, Vector params, String pageId,
			String arrayId,int pageSize,int currentPage) {
		HttpServletRequest request =  HttpRequestFactory.getRequest();
		String pageNumStr = request.getParameter("pageNum");
		String numPerPageStr = request.getParameter("numPerPage");
		Pager pager = null;
		if (request.getSession().getAttribute(pageId) != null&& StringUtils.isNotEmpty(request.getSession().getAttribute(pageId).toString())) {
			pager = (Pager) request.getSession().getAttribute(pageId);
		} else {
			pager = new Pager(10, 10);
		}
		
		pager.setCurrentPage(pageSize);
		pager.setPageSize(currentPage);
		
		request.getSession().setAttribute(pageId, "");
		List list = DBHelper.list(sql, params, pager);
		request.getSession().setAttribute(pageId, pager);
		if (StringUtils.isEmpty(arrayId)) {
			arrayId = "list";
		}
		request.setAttribute(arrayId, list);
	}

	
	/**
	 * 获取服务器时间
	 */
	public String getTime() throws Exception {
		HttpServletRequest request = HttpRequestFactory.getRequest();
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		request.setAttribute("ajax", dateFormat.format(date));
		return "ajax";
	}
	
	/**
	 * 根据ID查找记录
	 * 
	 * @param id_name
	 *           表id名称 
	 * @param table_name
	 *            表名
	 * @param arrayId
	 *            List集合对象的ID
	 */
	public void simple_edit(String sql,String id_name,String table_name,String list_id){

		HttpServletRequest request =  ServletActionContext.getRequest();
		String id_value = getValue(request.getParameter("id"));
		if(StringUtils.isEmpty(sql)){
			sql = "select * from "+table_name+" t  where "+id_name+"=? ";
		}else{
			sql+=" where t."+id_name+"=? ";
		}

		Vector params = new Vector();
		params.add(id_value);
		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		List list = DBHelper.list(sql, params);
		request.setAttribute(list_id, list);
		ConncenFactory.colseConnection();
	}

	
	/**
	 * 根据ID查找记录
	 * 
	 * @param id_name
	 *           表id名称 
	 * @param table_name
	 *            表名
	 */
	public void simple_del(String id_name,String table_name){
		HttpServletRequest request =  ServletActionContext.getRequest();
		String idstr = getValue(request.getParameter("idstr"));
		idstr = idstr.substring(0, idstr.length()-1);
		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		String sql =  "delete from "+table_name+" where "+id_name+" in ("+idstr+")";
		boolean b = false;
		try {
			b = DBHelper.execute(sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			setAjaxBoolean(b);
			ConncenFactory.colseConnection();
		}
	}

	
	/**
	 * 根据ID查找记录
	 * 
     * @param id_name
	 *            表id名称
	 * @param param
	 *           根据param字符串 获取id 
	 * @param table_name
	 *            表名
	 */
	public void simple_editCommit(String id_name,String param,String table_name){
		HttpServletRequest request =  ServletActionContext.getRequest();
		String id=getValue(request.getParameter(param));
		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		Map map = new HashMap();
		this.setInsertOrUpdateParams(map);
		String con=" where "+id_name+"='"+id+"'";
		boolean b = false;
		try {
			b = DBHelper.update(table_name, map, con);
			ConncenFactory.commit();
		} catch (Exception e) {
			ConncenFactory.rollback();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.setAjaxBoolean(b);
			ConncenFactory.colseConnection();
		}
	}
	
	public void simple_add(String id_name, String id_value, String tabel_name){
		HttpServletRequest request =  ServletActionContext.getRequest();
		Map map =  new HashMap();
		setInsertOrUpdateParams(map);
		if(StringUtils.isEmpty(id_value)){
			id_value=this.getGenerateId();//
		}

		map.put(id_name,id_value);
		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		boolean b = false;
		try {
			b = DBHelper.add(tabel_name, map);
			ConncenFactory.commit();
		} catch (Exception e) {
			ConncenFactory.rollback();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			setAjaxBoolean(b);
			ConncenFactory.colseConnection();
		}
	}
	
	
	public void simple_list(String sqlstr,String table_name,Map m){
		HttpServletRequest request =  ServletActionContext.getRequest();
		StringBuilder sql = new StringBuilder("");
		if(StringUtils.isEmpty(sqlstr)){
			sql.append("select * from "+table_name+"  where 1=? ");
		}else{
			sql.append(sqlstr);
		}


		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		int numPerPage = Integer.parseInt(request.getParameter("numPerPage"));
		Vector params = new Vector();
		params.add("1");

		Iterator it = m.keySet().iterator();
		String col ="";
		String value="";
		while (it.hasNext()) {
			col = (String) it.next();
			value = this.getValue(request.getParameter(col));
			if(!StringUtils.isEmpty(value)){
				if(m.get(col).toString().equals("equal")){
					sql.append(" and "+col+" = ? ");
					params.add(value);
				}
				
				if(m.get(col).toString().equals("like")){
					sql.append(" and "+col+" like ? ");
					params.add("%"+value+"%");
				}
				
			}
			
		}

			
		
		Pager pager = new Pager();
		pager.setPageSize(numPerPage);
		pager.setCurrentPage(pageNum);

		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		List list = DBHelper.list(sql.toString(), params, pager);

		request.setAttribute("list", list);
		
		request.setAttribute("pager", pager);
		ConncenFactory.colseConnection();
	}
	
	public void simple_ajax_list(String sqlstr,String table_name,Map m){
		HttpServletRequest request =  ServletActionContext.getRequest();
		StringBuilder sql = new StringBuilder("");
		if(StringUtils.isEmpty(sqlstr)){
			sql.append("select * from "+table_name+"  where 1=? ");
		}else{
			sql.append(sqlstr);
		}
		Vector params = new Vector();
		params.add("1");

		Iterator it = m.keySet().iterator();
		String col ="";
		String value="";
		while (it.hasNext()) {
			col = (String) it.next();
			value = this.getValue(request.getParameter(col));
			if(!StringUtils.isEmpty(value)){
				if(m.get(col).toString().equals("equal")){
					sql.append(" and "+col+" = ? ");
					params.add(value);
				}
				
				if(m.get(col).toString().equals("like")){
					sql.append(" and "+col+" like ? ");
					params.add("%"+value+"%");
				}
				
			}
			
		}

		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		List list = DBHelper.list(sql.toString(), params);
        this.setAjaxList(list);
		ConncenFactory.colseConnection();
	}
	
	/**
	 * 获取最大id信息SSS
	 * @param id_name
	 * @param table_name
	 * @return
	 */
	public String getMaxId(String id_name, String table_name){
		String id= "";
		String sql = "select max("+id_name+") as max from "+table_name;
		ConncenFactory.setConnection(DBConnection.getConnection());// 设置连接
		List list = DBHelper.list(sql);
		if(list!=null){
			id = (Integer.parseInt(((Map)list.get(0)).get("max").toString())+1)+""; 
		}
		ConncenFactory.colseConnection();
		return id;
	}
	

	/***
	 * 动态获取页面参数值
	 */

	@SuppressWarnings("unchecked")
	public Map getRequestParams() {
      Map paramsMap=new HashMap();
		HttpServletRequest request = HttpRequestFactory.getRequest();
		Map map = request.getParameterMap();
		Set s = map.keySet();
		Iterator it = s.iterator();
		String col = "";
		while (it.hasNext()) {
			col = (String) it.next();
			String value = getValue(request.getParameter(col));
			paramsMap.put(col, value);
		}
		return paramsMap;
	}
	
	/**
	 * 从定向发送请求
	 * @param url
	 * @throws Exception
	 */
	public void sendRedirect(String url) throws Exception {
		ServletActionContext.getResponse().sendRedirect(url);
	}
	
}
